<!--
 * Copyright © 2023
 * @Author: zhangxiang
 * @Date: 2023-07-06 15:33:47
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-07-23 11:29:27
 * @Description:
 *
-->

<template>
  <el-form
    ref="form"
    class="create-huawei"
    :rules="rules"
    :model="form"
    label-width="auto"
    size="medium"
  >
    <el-form-item
      v-if="scene != 'orchestrate'"
      class="item"
      label="云服务商"
      prop="cloudProvider"
    >
      <el-select
        v-model="form.cloudProvider"
        placeholder="请选择云服务商"
        style="width: 100%"
        :disabled="true"
      >
        <el-option
          v-for="item in cloudProviderOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item
      v-if="scene != 'orchestrate'"
      class="item right"
      label="云账户"
      prop="cloudAccountName"
    >
      <el-select
        v-model="form.cloudAccountName"
        placeholder="请选择云账户"
        style="width: 100%"
        no-data-text="请先选择合适的云服务商"
        :loading="loadingCloudAccountName"
        @change="cloudAccountNameChange"
      >
        <el-option
          v-for="item in cloudAccountNameOptions"
          :key="item.cloudAccountName"
          :label="item.cloudAccountName"
          :value="item.cloudAccountName"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="子网名称" prop="name">
      <el-input v-model="form.name" placeholder="请输入子网名称" />
    </el-form-item>
    <el-form-item class="item" label="区域" prop="cpRegionId">
      <el-select
        v-model="form.cpRegionId"
        placeholder="请选择区域"
        no-data-text="请选择合适的云服务商"
        style="width: 100%"
        @change="regionChange"
      >
        <el-option
          v-for="item in regionOptions"
          :key="item.cpId"
          :label="item.desc"
          :value="item.cpId"
        />
      </el-select>
    </el-form-item>
    <el-form-item class="item right" label="可用区" prop="zone">
      <el-select
        v-model="form.zone"
        placeholder="请选择可用区"
        no-data-text="请先选择区域"
        style="width: 100%"
      >
        <el-option
          v-for="item in zoneOptions"
          :key="item.key"
          :label="item.text"
          :value="item.key"
        />
      </el-select>
    </el-form-item>
    <el-form-item
      v-if="scene != 'orchestrate'"
      label="网络"
      prop="network"
    >
      <el-select
        v-model="form.network"
        placeholder="请选择网络"
        style="width: 100%"
        no-data-text="请先选择合适的云账户及区域"
        @change="networkChange"
      >
        <el-option
          v-for="item in networkOptions"
          :key="item.cpId"
          :label="item.name"
          :value="item.cpId"
        />
      </el-select>
      <div
        v-if="networkCidr"
        style="line-height: 25px; margin: 5px 0 0 15px; color: #999"
      >
        网段：{{ networkCidr }}
      </div>
    </el-form-item>
    <el-form-item label="子网网段" prop="cidr">
      <Cidr
        :cidr.sync="form.cidr"
        :explain="'子网网段必须是其所属VPC网段的子集且掩码需在16位到29位之间。<br/>例如，VPC 的网段为192.168.0.0/16，该 VPC 下的子网网段为 192.168.0.0/16 ~ 192.168.0.0/29。'"
      />
    </el-form-item>
    <el-form-item label="描述" prop="desc">
      <el-input
        v-model="form.desc"
        placeholder="请输入描述"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
  </el-form>
</template>

<script>
import { isEmptyString } from '@/utils/index'
import { getRegionList, queryVPC } from '@/api/cn-resource'
import resSelectorMixin from '@/views/mixin/resSelector.js'
import Cidr from './Cidr.vue'

export default {
  name: 'CreateHuawei',
  components: {
    Cidr
  },
  mixins: [resSelectorMixin],
  props: {
    cloudSelect: {
      type: String,
      default: '华为云'
    },
    scene: {
      type: String,
      default: 'create'
    },
    info: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    /**
     * @description: 检验子网网段
     * @param {*} rule
     * @param {*} value
     * @param {*} callback
     * @return {*}
     */
    var validateCidr = (rule, value, callback) => {
      const arr1 = this.form.cidr.split('/')
      if (arr1.length > 1) {
        const arr2 = arr1[0].split('.')
        if (arr2.length === 4) {
          if (
            !isEmptyString(arr1[1]) &&
            !isEmptyString(arr2[0]) &&
            !isEmptyString(arr2[1]) &&
            !isEmptyString(arr2[2]) &&
            !isEmptyString(arr2[3])
          ) {
            callback()
          } else {
            callback(new Error('请输入完整的子网网段'))
          }
        } else {
          callback(new Error('请输入子网网段'))
        }
      } else {
        callback(new Error('请输入子网网段'))
      }
    }
    return {
      cloudProviderType: 'public',
      skipGetCloudAccount: false,
      networkOptions: [],
      networkCidr: '', // 网段
      regionOptions: [],
      zoneOptions: [],
      form: {
        cloudProvider: '',
        cloudAccountName: '',
        name: '',
        cpRegionId: '', // 区域
        zone: '', // 可用区
        network: '',
        cidr: '',
        desc: ''
      },
      // 校验规则
      rules: {
        cloudProvider: [
          { required: true, message: '请选择云服务商', trigger: 'change' }
        ],
        cloudAccountName: [
          { required: true, message: '请选择云账户', trigger: 'change' }
        ],
        name: [{ required: true, message: '请输入子网名称', trigger: 'blur' }],
        cpRegionId: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        zone: [{ required: true, message: '请选择可用区', trigger: 'change' }],
        network: [{ required: true, message: '请选择网络', trigger: 'change' }],
        cidr: [{ required: true, validator: validateCidr }]
      }
    }
  },
  computed: {
    /**
     * @description: 网络相关参数
     * @return {*}
     */
    vpcParam() {
      return {
        cloudProvider: this.form.cloudProvider,
        cloudAccountName: this.form.cloudAccountName,
        cpRegionId: this.form.cpRegionId
      }
    }
  },
  watch: {
    /**
     * @description: 监听
     * @return {*}
     */
    info: {
      handler(newVal) {
        if (newVal) {
          this.form = Object.assign(this.form, this.info)
        }
      },
      immediate: true,
      deep: true
    },
    /**
     * @description: 监听网络相关参数
     * @return {*}
     */
    vpcParam: {
      handler(newVal) {
        if (
          newVal.cloudProvider &&
          newVal.cloudAccountName &&
          newVal.cpRegionId
        ) {
          this.getVPCList()
        }
      },
      immediate: true,
      deep: true
    },
    /**
     * @description: 云商监听
     * @return {*}
     */
    'form.cloudProvider': {
      handler(newVal) {
        if (newVal) {
          // 获取区域
          this.getRegionList()
        }
      },
      immediate: true
    },
    cloudSelect: {
      handler(newVal) {
        if (newVal) {
          this.form.cloudProvider = this.cloudSelect
        }
      },
      immediate: true
    }
  },
  created() {
    this.skipGetCloudAccount = this.scene === 'orchestrate'
  },
  methods: {
    /**
     * @description: 获取区域
     * @return {*}
     */
    getRegionList() {
      getRegionList({
        keyword: this.form.cloudProvider,
        pageNum: 1,
        pageSize: 100
      }).then((res) => {
        if (res.data) {
          this.regionOptions = Array.isArray(res.data.data)
            ? res.data.data
            : []
          if (this.form.cpRegionId) {
            this.findZoneOptions()
          }
        } else {
          this.regionOptions = []
        }
      })
    },
    /**
     * @description: 区域变化
     * @param {*} val
     * @return {*}
     */
    regionChange(val) {
      this.form.zone = ''
      this.findZoneOptions()
      this.form.network = ''
    },
    /**
     * @description: 查找可用区
     * @return {*}
     */
    findZoneOptions() {
      // 查找已选择
      const regionSelect = this.regionOptions.find((item) => {
        return this.form.cpRegionId === item.cpId
      })
      // 设置可用区选项
      if (regionSelect && Array.isArray(regionSelect.zones)) {
        this.zoneOptions = regionSelect.zones.filter((item) => {
          return item.val
        })
      } else {
        this.zoneOptions = []
      }
    },
    /**
     * @description: 云账户切换
     * @param {*} val
     * @return {*}
     */
    cloudAccountNameChange(val) {
      this.form.network = ''
    },
    /**
     * @description: 网络选择回调
     * @param {*} val
     * @return {*}
     */
    networkChange(val) {
      const networkFind = this.networkOptions.find((item) => {
        return item.cpId === val
      })
      this.networkCidr =
        networkFind && networkFind.cidr ? networkFind.cidr : ''
    },
    /**
     * @description: 获取网络
     * @return {*}
     */
    getVPCList() {
      queryVPC({
        cloudProvider: this.form.cloudProvider,
        cloudAccountName: this.form.cloudAccountName,
        region: this.form.cpRegionId
      }).then((res) => {
        this.networkOptions = Array.isArray(res.data) ? res.data : []
      })
    },
    /**
     * @description: 校验
     * @return {*}
     */
    validateForm(callback) {
      this.$refs.form.validate((valid, obj) => {
        if (valid) {
          callback(this.form)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.create-huawei {
  .item {
    display: inline-block;
    width: calc(50% - 10px);
    &.right {
      margin-left: 20px;
    }
  }
}
</style>
